package com.starmark.sys.login.provider.service.impl;

import cn.hutool.core.util.StrUtil;
import com.google.code.kaptcha.impl.DefaultKaptcha;
import com.starmark.core.framework.util.RedisUtils;
import com.starmark.sys.login.provider.service.ICaptchaService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;


import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.Objects;
import java.util.Optional;

/**
 * 验证码服务
 *
 * @author starmark
 * @date 2020/5/30  下午9:45
 */

@Service
public class CaptchaServiceServiceImpl implements ICaptchaService {


    /**
     * 1、验证码工具
     */
    @Autowired
    DefaultKaptcha defaultKaptcha;

    @Autowired
    private RedisUtils redisUtils;

    @Override
    public void createCaptcha(String id, HttpServletResponse httpServletResponse) throws IOException {
        byte[] captchaChallengeAsJpeg;
        ByteArrayOutputStream jpegOutputStream = new ByteArrayOutputStream();
        // 生产验证码字符串并保存到session中
        String createText = defaultKaptcha.createText();
        //验证码已过期
        redisUtils.set(id, createText, 120);
        // 使用生产的验证码字符串返回一个BufferedImage对象并转为byte写入到byte数组中
        BufferedImage challenge = defaultKaptcha.createImage(createText);
        ImageIO.write(challenge, "jpg", jpegOutputStream);

        // 定义response输出类型为image/jpeg类型，使用response输出流输出图片的byte数组
        captchaChallengeAsJpeg = jpegOutputStream.toByteArray();

        httpServletResponse.setDateHeader("Expires", 0);
        httpServletResponse.setHeader("Cache-Control", "no-store, no-cache, must-revalidate");
        httpServletResponse.addHeader("Cache-Control", "post-check=0, pre-check=0");
        httpServletResponse.setHeader("Pragma", "no-cache");
        httpServletResponse.setContentType("image/jpeg");
        ServletOutputStream responseOutputStream = httpServletResponse.getOutputStream();
        responseOutputStream.write(captchaChallengeAsJpeg);
        responseOutputStream.flush();
        responseOutputStream.close();

    }

    @Override
    public int checkCaptcha(String id, String rightCode) {

        String checkRightCode= Optional.ofNullable(redisUtils.get(id)).orElse("")+"";
        if(StrUtil.isBlank(checkRightCode)){
            //验证码不存在，或已过期
            return -1;
        }
        return  Objects.equals(checkRightCode,rightCode)?0:1;
    }
}
